<!-- 专家选择器 -->
<template>
  <el-select
    v-model="currentID"
    v-loadMore="selectLoadMore"
    filterable
    remote
    :placeholder="!options.length ? '暂无医生可选' : '请选择医生'"
    clearable
    @change="handleChange"
    :remote-method="remoteMethod"
    :disabled="disabled"
    :loading="loading"
    style="width: 100%"
  >
    <el-option
      v-for="item in options"
      :key="item.id"
      :value="item.id"
      :label="item.userName + (item.deptname ? `(${item.deptname})` : ``)"
    >
  </el-option>
  </el-select>
</template>

<script>
import { listExpert, getExpert } from "@/api/expert/expert";
import { arrayUnique } from "@/utils/ruoyi";

export default {
  props: {
    defaultValue: {
      type: Number | String,
    },
    comId: {
      type: Number | String
    },
    // 是否有处方权-中医审核 0-否 1-是
    prescriptionFlag: {
      type: Number,
      default: 0
    },
    disabled: {
      type: Boolean,
      default: false,
    }
  },
  watch: {
    defaultValue(nval) {
      this.currentID = nval;
      this.backShow(); // 回显
    },
    comId(nval, oval) {
      console.log(nval, oval);
      this.$emit("update:defaultValue", undefined); // 单位选择改变，清空已选专家
      this.remoteMethod('')
    }
  },
  data() {
    return {
      currentID: null,
      options: [],
      getParams: {
        pageNum: 1,
        pageSize: 10,
        apStatus: 1,
        searchValue: undefined,
      },
      total: 0,
      loading: false,
    };
  },
  async created() {
    this.currentID = this.defaultValue;
    await this.getList();
    this.backShow(); // 回显
  },
  methods: {
    async getList() {
      const { rows, total } = await listExpert({...this.getParams,comId: this.comId, prescriptionFlag: this.prescriptionFlag});
      this.total = total;
      if (this.getParams.pageNum === 1) {
        this.options = [];
      }
      this.options = arrayUnique([...this.options, ...rows], "id");
    },
    // 下拉加载更多
    selectLoadMore() {
      if (this.options.length < this.total) {
        this.getParams.pageNum++;
        this.getList();
      }
    },
    async remoteMethod(query) {
      this.loading = true;
      this.getParams.pageNum = 1;
      this.getParams.pageSize = 10;
      this.getParams.searchValue = query;
      await this.getList();
      this.loading = false;
    },
    handleChange(e) {
      this.$emit("update:defaultValue", e);
      const item = this.options.find(v=> v.id === e)
      this.$emit("change", item);
    },
    // 回显判断,是否存在于数组中,不存在则查询详情unshift进去
    backShow() {
      if (this.currentID) {
        const _item = this.options.find((v) => v.id === this.currentID);
        if (!_item) {
          getExpert(this.currentID).then((res) => {
            if (res.data) {
              this.options = arrayUnique([res.data, ...this.options], "id");
            }
          });
        }
      }
    },
  },
};
</script>

<style lang="scss" scoped></style>
